using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using util;
using PXP.Core;

namespace TS
{
    class MainW : PXPForm, IWidget, IDockItem
    {
        private String loc = "C:\\Program Files\\Teamspeak2_RC2\\";
        private bool TSinstalled = true;
        private bool running = true;
        private Process tsC = new Process();
        private String apiLoc;
        private String appLoc;
        private Server ts;
        private Button cd = new Button();
        private Button mute = new Button();
        private Timer updateTimer = new Timer();
        private int upInterval = 200;
        private static void Main()
        {
            
            Application.Run(new MainW());
        }
        public MainW()
        {
            InitializeComponent(); 
        }
        private void InitializeComponent()
        {
             //setup PxPform
    
                this.ClientSize = new System.Drawing.Size(310, 575);
                this.Name = "PXPTeamSpeak";
                this.Text = "TeamSpeak Remote";

            //seting up 
            setUpLocs();
            
            if (TSinstalled)
            {
                tsC.StartInfo.FileName = loc + "client_sdk\\tsControl.exe";
                tsC.StartInfo.UseShellExecute = false;
                tsC.StartInfo.RedirectStandardOutput = true;
                tsC.StartInfo.CreateNoWindow = true;
                testRunning();
            }
            if (TSinstalled && running)//setUpLocs() checks if TS is installed if it is we will set up widge with the following code
            {
                //SET UP TS Server and load teh data into a Tree
                ts = new Server(loc);
                ts.addToForm(this);

                //set up conect/disconect button
                if (ts.isConected())
                    cd.Text = "Disconnect";
                else
                    cd.Text = "Connect";
                cd.Click += new EventHandler(cd_Click);
                cd.Location = new System.Drawing.Point(ts.getTreeLoc().X, ts.getTreeLoc().Y + ts.getTreeSize().Height + 10);
                this.pnlMainContainer.Controls.Add(cd);

                //set up mute/unmute button
                mute.Text = "";
                mute.ImageList = new ImageList();
                mute.ImageList.ImageSize = new System.Drawing.Size(40, 40);
                mute.ImageList.Images.Add(TS.Properties.Resources.speakerOn);
                mute.ImageList.Images.Add(TS.Properties.Resources.speakerOff);
                mute.ImageIndex = 0;
                mute.Size = new System.Drawing.Size(20, 20);
                mute.Location = new System.Drawing.Point(240 - mute.Size.Width, cd.Location.Y);
                mute.Size = new System.Drawing.Size(mute.Image.Size.Width, mute.Image.Size.Height);
                mute.Click += new EventHandler(mute_Click);
                this.pnlMainContainer.Controls.Add(mute);

                //start up-date thread
                updateTimer.Interval = upInterval;
                updateTimer.Tick += new EventHandler(updateTimer_Tick);
                updateTimer.Start();
            }
            else
            {
                if (!TSinstalled)
                {
                    Label l = new Label();
                    l.Location = new System.Drawing.Point(10, 10);
                    l.Text = "TeamSpeak seems not to be installed.\n Please, install TeamSpeak and restart PXP.";
                    l.Size = new System.Drawing.Size(250, 300);
                    l.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
                    this.pnlMainContainer.Controls.Add(l);
                }
                if (!running  && TSinstalled)
                {
                    loadNotRunningConfig();
                }
            }
        }
        private void loadNotRunningConfig()
        {
            Label l = new Label();
            l.Text = "TeamSpeak seems not to be running.\n\n I can start TeamSpeak but it may kick you out of your game.\n\n  Do you want me to start TeamSpeak?";
            l.Size = new System.Drawing.Size(250, 300);
            l.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.pnlMainContainer.Controls.Add(l);
            Button run = new Button();
            run.Text = "Start TeamSpeak";
            run.Location = new System.Drawing.Point(55, l.Location.Y + l.Size.Height + 10);
            run.Size = new System.Drawing.Size(run.Size.Width * 2, run.Size.Height);
            run.Click += new EventHandler(run_Click);
            this.pnlMainContainer.Controls.Add(run);
        }

        //set up methods
        private void testRunning()
        {
            tsC.StartInfo.Arguments = "get_user_info";
            tsC.Start();
            tsC.WaitForExit();
            if (tsC.StandardOutput.ReadLine().Equals("ERROR -1000 TEAMSPEAK CLIENT NOT FOUND"))
                running = false;
            else
                running = true;
        }
        private void setUpLocs()
        {
            if (File.Exists(loc + "TeamSpeak.exe") && File.Exists(loc + "client_sdk\\tsControl.exe"))
            {
                apiLoc = loc + "client_sdk\\tsControl.exe";
                appLoc = loc + "TeamSpeak.exe";
            }
            else
            {
                Object a = null;
                try { a = Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("Classes").OpenSubKey("teamspeak").OpenSubKey("Shell").OpenSubKey("Open").OpenSubKey("command").GetValue(""); }
                catch (Exception e){ TSinstalled = false; }
                if (TSinstalled)
                {
                    String s = a.ToString();
                    char[] dill = { '\"' };
                    String[] split = s.Split(dill);
                    dill[0] = '\\';
                    String temp = split[0];
                    split = temp.Split(dill);
                    temp = "";
                    foreach (String x in split)
                        if (!x.Trim().EndsWith(".exe"))
                            temp += x + "\\";
                    loc = temp;
                    apiLoc = loc + "client_sdk\\tsControl.exe";
                    appLoc = loc + "TeamSpeak.exe";
                    if (!File.Exists(apiLoc) && !File.Exists(appLoc))
                        TSinstalled = false;
                }
            }
        }

        //events
        private void updateTimer_Tick(object o, EventArgs e)
        {
            testRunning();
            if (running)
            {
                ts.update();
                if (ts.isConected())
                    cd.Text = "Disconnect";
                else
                    cd.Text = "Connect";
                cd.Update();
            }
            else
            {
                this.pnlMainContainer.Controls.Clear();
                updateTimer.Stop();
                loadNotRunningConfig();
            }
        }
        private void cd_Click(Object o, EventArgs e)
        {
            if (ts.isConected())
            {
                tsC.StartInfo.FileName = apiLoc;
                tsC.StartInfo.Arguments = "DISCONNECT";
                tsC.Start();
                cd.Text = "Connect";
            }
            else
            {
                conectDia dia = new conectDia();
                dia.ShowDialog();
                if (dia.exit_opp == conectDia.OK)
                {
                    string ip = dia.ip;
                    String nick = dia.nick;
                    String logname = dia.logname;
                    String pass = dia.pass;
                    tsC.StartInfo.Arguments = "CONNECT " + ip.Trim() + "?nickname=" + nick.Trim() + "?loginname=" + logname.Trim() + "?password=" + pass.Trim();
                    tsC.Start();
                    tsC.WaitForExit();
                    ts.update();
                    cd.Text = "Disconnect";
                }
            }
        }
        private void mute_Click(Object o, EventArgs e)
        {
            if (mute.ImageIndex == 0)//speaker on
            {
                mute.ImageIndex = 1;
                tsC.StartInfo.Arguments = "mute";
                tsC.Start();
            }
            else
            {
                mute.ImageIndex = 0;
                tsC.StartInfo.Arguments = "unmute";
                tsC.Start();
            }
        }
        private void run_Click(object o, EventArgs e)
        {
            Process p = new Process();
            p.StartInfo.FileName = appLoc;
            p.Start();
            this.pnlMainContainer.Controls.Clear();
            this.Update();
            while (running == false)
                testRunning();
            
            running = true;
            InitializeComponent();
            this.Update();
        }

        #region IWidget Members
        private ICore core;
        object IWidget.GetFeatureInstance(string featureName)
        {
            switch (featureName)
            {
                case "Dock":
                    return this;
                default:
                    break;
            }

            return null;
        }
        string IWidget.GetWidgetAuthor()
        {
            return "Ross E Lanes";
        }
        string IWidget.GetWidgetCompany()
        {
            return "Inner Circle";
        }
        List<string> IWidget.GetWidgetFatures()
        {
            List<string> features = new List<string>();
            features.Add("Dock");
            return features;
        }
        Guid IWidget.GetWidgetGUID()
        {
            //this may need to be changed not shure how it works
            return new Guid("5ca2a57d-2f6f-4b97-bd9e-157da5e8aea6");
        }
        string IWidget.GetWidgetName()
        {
            return "TeamSpeak Remote";
        }
        string IWidget.GetWidgetURL()
        {
            return "";
        }
        Version IWidget.GetWidgetVersion()
        {
            return System.Reflection.Assembly.GetAssembly(this.GetType()).GetName().Version;
        }
        string IWidget.GetWidgetWebsite() {return "";} //dont have one...}
        void IWidget.OnLoad(ICore core, string data) { this.core = core; }// Keep reference to the core}
        void IWidget.OnStart(){}
        void IWidget.OnStop(){this.Close();}
        void IWidget.OnUnload(string data){}

        #endregion

        #region IDockItem Members

        System.Drawing.Image IDockItem.GetImage(string state)
        {
            return TS.Properties.Resources.teamspeak;
        }
        string IDockItem.GetText()
        {
            return "TS Remote";
        }
        public ToolStripMenuItem GetContextMenuItem()
        {
            return null;
        }
        public void OnMouseDown(MouseEventArgs e)
        {
            
            this.Show();
            this.TopMost = true;
            this.BringToFront();
            this.TopMost = false;
        }
        public void OnMouseUp(MouseEventArgs e)
        {
        }
        public void OnMouseMove(MouseEventArgs e)
        { }
        #endregion
    }
}
